#!groovy

pipeline {
	// 定义pipeline在哪里运行
	agent {node {label 'master'}}
	
	// 添加全局环境变量,比如git命令在/usr/bin下面,则可以在下面直接使用git命令
	environment {
		PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin"
	}

	// 参数区域
	parameters {
		// 声明一个选项参数
		choice(
			choices: 'dev\nprod',
            description: 'Choose deploy environment',
            name: 'deploy_env'
		// 声明一个文本参数
		)
		string (
			name: 'branch', 
			defaultValue: 'master', 
			description: 'Fill in your ansible repo branch'
		)
	}
	
	// 最外层stages,用来包裹所有stage
	stages {
		// 第一个模块: 从git检出项目
		stage ("Pull deploy code") {
			steps {
				// sh代表执行引号内的shell命令
				sh 'git config --global http.sslVerify false'
				// dir用来设置命令在哪个路径下执行, ${env.WORKSPACE}代表jenkins默认的工作空间, 一般为 /var/lib/jenkins/workspace/
				dir ("${env.WORKSPACE}") {
					// 拉取gitlab上的ansible playbook剧本
					git branch: 'master', 
					credentialsId: '4c03245f-4976-41da-aa3a-08d74f8311a4', 
					url: 'https://gitlab.example.com/root/ansible-playbook-repo.git'
			    }
			}
		}
		
		// 第二个模块: 检查环境并打印相关信息
		stage ("Check env") {
			steps {
				sh """
				# 关闭当前环境变量的输出值,避免无用的输出干扰log日志
				set +x
				# 获取当前用户赋值给user,jenkins的当前用户是在 /etc/sysconfig/jenkins配置文件中的JENKINS_USER设置的
				user=`whoami`
				if [ $user == deploy ]
				then
					echo "[INFO] Current deployment user is $user"
					# 加载python及ansible相关环境
					source /home/deploy/.py3-a2.5-env/bin/activate
                    source /home/deploy/.py3-a2.5-env/ansible/hacking/env-setup -q
					echo "[INFO] Current python version"
                    python --version
                    echo "[INFO] Current ansible version"
                    ansible-playbook --version
                    echo "[INFO] Remote system disk space"
                    ssh root@test.example.com df -h
                    echo "[INFO] Rmote system RAM"
                    ssh root@test.example.com free -m
				else
					echo "Deployment user is incorrect, please check"
				fi
				
				set -x
				"""
			}
		}
		
		// 第三个模块: 执行ansible playbook操作远程客户主机部署项目
		stage ("Ansible deployment") {
			steps {
				input "Do you approve the deployment?"
				dir ("${env.WORKSPACE}/wordpress_playbooks") {
					echo "[INFO] Start deployment"
					sh """
					set +x
					source /home/deploy/.py3-a2.5-env/bin/activate
                    source /home/deploy/.py3-a2.5-env/ansible/hacking/env-setup -q
					# 使用-e可以设置一些启动变量
					ansible-playbook -i inventory/$deploy_env ./deploy.yml -e project=wordpress -e branch=$branch -e env=$deploy_env
					set -x
					"""
					echo "[INFO] Deployment finished..."
				}
			}
		}
	
	}
}

